
//
//  TrainDetailVc.m
//  SpiritWalk
//
//  Created by shange1999 on 16/3/14.
//  Copyright © 2016年 王鑫. All rights reserved.
//

#import "TrainDetailVc.h"

#import "CoreDataManager.h"

#import "Tran+CoreDataProperties.h"
@interface TrainDetailVc ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableviewSelf;
@property(nonatomic,strong)NSMutableArray *nameArr;
@property(nonatomic,strong) TrainHeadView *backView;
@property(nonatomic,strong)NSMutableArray *MVarr;

@property(nonatomic,strong)CoreDataManager *manager;
@property(nonatomic,copy)NSArray *arr;
@property(nonatomic,strong)TrainDTVcHeadModel *headReceiveModel;

@end

@implementation TrainDetailVc

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.nameArr=[NSMutableArray array];
        self.MVarr =[NSMutableArray array];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor =[UIColor whiteColor];
    [self createData];
    [self createView];
    
    
    self.title=self.titleStr;
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-weishoucang.png"] style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    self.manager=[CoreDataManager manager];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tran" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //谓词
    //包含语句
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title CONTAINS %@ and num=0",self.titleStr];
    [fetchRequest setPredicate:predicate];
    self.arr=[self.manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    NSLog(@"+++%@",self.arr);
    if (self.arr.count==0) {

        
     self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-weishoucang.png"] style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
        
        
    }
    else{
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-shoucangyishoucang-copy.png"] style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
        
        
    }
    


    
    
    
}

-(void)click:(UIBarButtonItem *)button{
    self.manager=[CoreDataManager manager];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tran" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //谓词
    //包含语句
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title CONTAINS %@ and num=0",self.titleStr];
    [fetchRequest setPredicate:predicate];
    self.arr=[self.manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    NSLog(@"+++%@",self.arr);
    if (self.arr.count==0) {
        Tran *tar=[NSEntityDescription insertNewObjectForEntityForName:@"Tran"
                                                  inManagedObjectContext:self.manager.managedObjectContext];
        
        tar.title=self.titleStr;
        tar.num=@0;
         [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"iconfont-shoucangyishoucang-copy.png"]];
        //调用保存方法
        [self.manager saveContext];
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
        
      
        
        
    }
    else{
        
        for (Tran *tran in self.arr) {
            
            tran.num=@1;
          
            
            [self.manager saveContext];
            
        }

        
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"取消收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
        
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"iconfont-weishoucang.png"]];
  
    }
    
    
}


-(void)createView{
    self.tableviewSelf=[[UITableView alloc ]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64-49) style:0];
    self.tableviewSelf.rowHeight=60;
    [self.view addSubview:self.tableviewSelf];
    self.tableviewSelf.separatorStyle = NO;
    self.tableviewSelf.delegate=self;
    self.tableviewSelf.dataSource=self;
   
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([TrainDetailTABCell class]) bundle:nil];    //找到nib文件
    [self.tableviewSelf registerNib:nib forCellReuseIdentifier:@"mytableviewCell"];   //注册,在nib文件里面找到当前需要注册的cell
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.nameArr.count>0) {
        return self.nameArr.count;
    }
   return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TrainDetailTABCell *cell =[tableView dequeueReusableCellWithIdentifier:@"mytableviewCell" forIndexPath:indexPath];
    cell.selectionStyle=NO;
    cell.number.text =[NSString stringWithFormat:@"%d",((int)indexPath.row+1)];
    cell.receiveModel = self.nameArr[indexPath.row];
    return cell;
    
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TrainDTVMVModel *model =self.nameArr[indexPath.row];
    NSMutableArray *arr =model.resolve_list;   //数组
    TrainMvPlayVcc *vc =[[TrainMvPlayVcc alloc]init];
    vc.receiveArr = arr;
    vc.dayID = model.day_id;
    [self presentViewController:vc animated:YES completion:^{
    }];
  }
#pragma 分区
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
#pragma 分区的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * head =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    UILabel *title =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
   title.text =@"课程内容";
    title.textAlignment =NSTextAlignmentCenter;
    [head addSubview:title];
    return head;
}
#pragma mark 实现tableview上的图片的拉伸
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat width = self.view.frame.size.width; // 图片宽度
    CGFloat yOffset = scrollView.contentOffset.y;  // 偏移的y值
    if (yOffset < 0) {
        CGFloat totalOffset = 250 + ABS(yOffset);  //ABS绝对值
        CGFloat f = totalOffset / 250;
        self.backView.backImage.frame =  CGRectMake(- (width * f - width) / 2, yOffset, width * f, totalOffset); //拉伸后的图片的frame应该是同比例缩放。
//        self.backView.subject_name.frame =CGRectMake( (width * f - width) / 2+50, -yOffset+30, WIDTH-100, 50);
//        self.backView.traning_difficult.frame =CGRectMake( (width * f - width) / 2+50, -yOffset+50, WIDTH-100, 50);
//        self.backView.traning_day.frame =CGRectMake( (width * f - width) / 2+50, -yOffset+50, WIDTH-100, 50);
//        self.backView.traning_site.frame =CGRectMake( (width * f - width) / 2+50, -yOffset+50, WIDTH-100, 50);
//        self.backView.desc.frame =CGRectMake( (width * f - width) / 2+50, -yOffset+50, WIDTH-100, 50);
//        [self.backView.subject_name.superview layoutIfNeeded];//强制绘制
        //费
    }
}




#pragma 解析数据
-(void)createData{
    NSString *idStr =self.receiveId;
    NSString *usrStr=@"http://so.jianshen.so/Realtech/Course/courseDetail";
    NSDictionary *dic = @{@"courseId" : idStr,@"userId" : @"9607" };
    [Tool POST:usrStr parameters:dic black:^(id data) {
        _backView =[[TrainHeadView alloc ]initWithFrame:CGRectMake(0, 0, WIDTH, 250)];
        /********头部******/
        NSDictionary *dic =data[@"data"];
        TrainDTVcHeadModel *model =[[TrainDTVcHeadModel alloc]init];
        [model setValuesForKeysWithDictionary:dic];
        _backView.headReceiveModel = model;
        self.tableviewSelf.tableHeaderView = _backView;
        /***********TBV*********/
        self.nameArr  =[TrainDTVMVModel baseModelByArr:data[@"data"][@"day_list"]];
//        self.MVarr =[TrainDTVMVModel baseModelByArr:data[@"data"][@"day_list"][@""]];
               [self.tableviewSelf reloadData];
    }];
}


























- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
